package org.hotpotmaterial.code.controller.titanServices;

import java.util.Date;

import org.hotpotmaterial.anywhere.common.mvc.rest.basic.ResultDTO;
import org.hotpotmaterial.code.dto.ResultServiceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.changan.otp.app.client.ResultOfTokenDTO;
import com.changan.otp.app.client.TokenDTO;
import com.changan.otp.app.common.RestStatus;
import com.changan.otp.app.property.TitanServiceProperties;
import com.changan.otp.app.util.CryptionUtil;
import com.changan.otp.app.util.KeyUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 
 * @author Administrator
 *
 */
@Controller
@Api(value = "Services", description = "the Services API")
@RequestMapping(value = "/api/services")
public class ServicesController {

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private TitanServiceProperties titanProperties;

  @ApiOperation(value = "服务调用token", notes = "服务调用token", response = ResultDTO.class)
  @ApiResponses(value = {@ApiResponse(code = 200, message = "返回结果信息", response = ResultDTO.class),
      @ApiResponse(code = 401, message = "返回认证错误信息")})
  @GetMapping("/token/{serviceName}")
  public ResponseEntity<ResultDTO> getServiceToken(@PathVariable String serviceName) {
    String seccode = CryptionUtil.encrypt(titanProperties.getAppid(),
        KeyUtil.publicKeyBase64ToKey(titanProperties.getAppPubkey()));
    
    UriComponentsBuilder builder = UriComponentsBuilder
        .fromHttpUrl("http://" + titanProperties.getPlatform().getServiceUrl()
            + "/app_manage/v1/app_infos/" + titanProperties.getAppid() + "/check/token")
        .queryParam("appSeccode", seccode)
        .queryParam("serviceId", titanProperties.getPlatform().getServiceMap().get("file-service"));

    ResultOfTokenDTO tokend =
        restTemplate.getForObject(builder.build().encode().toUri(), ResultOfTokenDTO.class);

    TokenDTO tokendto = new TokenDTO();
    tokendto.setExpireAt(new Date(tokend.getExpired()));
    tokendto.setToken(tokend.getToken());

    return new ResponseEntity<ResultDTO>(
        new ResultServiceDTO().tokenDTO(tokendto).message(RestStatus.RESULT_SUCCESS.message()),
        HttpStatus.OK);
  }

}
